package com.lin.activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.lin.utils.Utils;
import com.lin.views.ListViewForCollection;
import com.lin.views.ListViewForFriendShare2;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.FriendsShareBean;

public class MyCollectionActivity extends FragmentActivity implements OnClickListener, ListViewForCollection.OnItemListViewEventListener{

	private FrameLayout mFrameLayoutBack;
	Session mSession;
	ListViewForCollection mListView;
	private EditText mEditText;
	private ImageView mImageView;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	int pagenum = 1;
	ArrayList<FriendsShareBean> dataList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		setContentView(R.layout.activity_my_collection);
		mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);

		mListView = (ListViewForCollection) findViewById(R.id.listview);
		mListView.addHeaderView(getLayoutInflater().inflate(R.layout.list_header_search, null));
		mEditText = (EditText) findViewById(R.id.et_search);
		mImageView = (ImageView) findViewById(R.id.iv_search);
		mImageView.setOnClickListener(this);
		mFrameLayoutBack = (FrameLayout) findViewById(R.id.framelayout_back);
		mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe);

		load(pagenum);

		mSwipeRefreshLayout.setColorSchemeResources(R.color.base_orange);
		mSwipeRefreshLayout.setRefreshing(true);
		mSwipeRefreshLayout.setEnabled(false);
		mFrameLayoutBack.setOnClickListener(this);
		mEditText.addTextChangedListener(textWatcher);
		dataList = new ArrayList<FriendsShareBean>();

		mListView.setOnItemListViewEventListener(this);
		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Utils.hidenKeyBoard(getApplicationContext(), mEditText);
				return false;
			}
		});

		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				// 当不滚动时
				case OnScrollListener.SCROLL_STATE_IDLE:
					String res = mEditText.getText().toString();
					if(TextUtils.isEmpty(res)) 

						// 判断滚动到底部
						if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
							pagenum++;
							load(pagenum);
							Toast.makeText(MyCollectionActivity.this, "正在加载新数据", Toast.LENGTH_SHORT).show();
						}
					break;
				}	
			}

			@Override
			public void onScroll(AbsListView absListView, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				mSwipeRefreshLayout.setEnabled(false);
				if (firstVisibleItem == 0)
					mSwipeRefreshLayout.setEnabled(true);
				else
					mSwipeRefreshLayout.setEnabled(false);
			}
		});

		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				String stringET = mEditText.getText().toString();
				if(TextUtils.isEmpty(stringET)) {
					dataList.clear();
					mSwipeRefreshLayout.setRefreshing(true);
					pagenum = 1;
					load(pagenum);
				} else {
					mSwipeRefreshLayout.setRefreshing(false);
				}
			}
		});
	}

	private void load(int pagenum) {
		mSession.GetStore(getApplicationContext(), mSession.getmUserBean().getUserid(), pagenum + "", "15",  new ResultReceiver<ArrayList<FriendsShareBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<FriendsShareBean> args) {
				// TODO Auto-generated method stub
				mSwipeRefreshLayout.setRefreshing(false);
				if(args != null) {
					dataList.addAll(args);
					mListView.setDataList(dataList);
					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
					mDatabaseHelperForChattingMap.insertFriendsShareBeanListCollection(args, mSession.getmUserBean().getUserid() + "");
					mDatabaseHelperForChattingMap.close();
				} else {

					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
					args = mDatabaseHelperForChattingMap.getFriendsShareBeanListCollection(mSession.getmUserBean().getUserid() + "");
					mDatabaseHelperForChattingMap.close();
					dataList.addAll(args);
					mListView.setDataList(args);
				}
			}

		}) ;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.framelayout_back:
			finish();
		case R.id.iv_search:
			String s = mEditText.getText().toString();
		}
	}

	@Override
	public void onItemAvatarLisener(FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, DynamicShareWallActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(Constants.KEY_DATA, maListInfo.getUserid());
		intent.putExtra("avatar", maListInfo.getPhoto());
		intent.putExtra("username", maListInfo.getNick_name());
		startActivity(intent);
	}

	@Override
	public void onItemClickListener(FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemUserDetailListener(FriendsShareBean maListInfo, int x,
			int y) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemGridViewClickListener(FriendsShareBean maListInfo,
			int position) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, FullScreenViewActivity.class);

		intent.putParcelableArrayListExtra("datalist", dataList);
		int index = dataList.indexOf(maListInfo);
		intent.putExtra("dataitem", index);
		intent.putExtra("position", position);
		startActivity(intent);

	}

	@Override
	public void onItemProClickListener(FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemCollectionClickListener(FriendsShareBean maListInfo,
			int x, int y) {
		// TODO Auto-generated method stub

	}

	private TextWatcher textWatcher = new TextWatcher() {  

		@Override    
		public void afterTextChanged(Editable s) {     
			// TODO Auto-generated method stub
			String res = s.toString();
			if(TextUtils.isEmpty(res)) {
				mListView.setDataList(dataList);
				return;
			}
			Pattern p = Pattern.compile(res, Pattern.CASE_INSENSITIVE); 
			ArrayList<FriendsShareBean> newFriendsShareBeanList = new ArrayList<FriendsShareBean>();
			boolean isAdded = false;
			for(Iterator<FriendsShareBean> iterator=dataList.iterator();iterator.hasNext();) {
				isAdded = false;
				FriendsShareBean mBean = iterator.next();
				Matcher m = p.matcher(mBean.getNick_name());
				if(m.find()) {
					mBean.setPositionNickNameStart(m.start());
					mBean.setPositionNickNameEnd(m.end());
					isAdded = true;
				}

				m = p.matcher(mBean.getContent());
				if(m.find()) {
					mBean.setPositionContentStart(m.start());
					mBean.setPositionContentEnd(m.end());
					isAdded = true;
				}
				if(isAdded == true) {
					newFriendsShareBeanList.add(mBean);
				}

			}

			mListView.setDataList(newFriendsShareBeanList);
			Log.d("TAG","afterTextChanged--------------->");   
		}   

		@Override 
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			Log.d("TAG","beforeTextChanged--------------->");  
		}  

		@Override    
		public void onTextChanged(CharSequence s, int start, int before,     
				int count) {     
			Log.d("TAG","onTextChanged--------------->");    

		}                    
	};  
}